import { Request, Response } from 'express';
import { AuthRequest } from '@/types';
import userService from '@/services/system/user.service';
import multer from 'multer';
import path from 'path';
import fs from 'fs';
import { promisify } from 'util';
import ExcelUtil from '@/utils/excel/excel.util';
import ApiResponse from '@/utils/api/api-response.util';
import { getLogger } from '@/utils/logger';
import deptService from '@/services/system/dept.service';
import roleService from '@/services/system/role.service';
import postService from '@/services/system/post.service';
import sysConfigService from '@/services/system/sys-config.service';
import { Log, BusinessType } from '@/decorators/Log';
import { RepeatSubmit } from '@/decorators/repeatSubmit.decorator';
import { RateLimit } from '@/decorators/rateLimit.decorator';

// 创建模块专用的日志记录器
const consoleLogger = getLogger("user-controller");
const logger = getLogger("user-controller", {
	console: false,
});



// 创建上传文件存储配置
const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    // 根据文件类型选择不同的上传目录
    let uploadDir = 'uploads/import';
    
    // 如果是头像，使用avatar目录
    if (file.fieldname === 'avatarfile') {
      uploadDir = 'uploads/avatar';
    }
    
    // 确保目录存在
    if (!fs.existsSync(uploadDir)) {
      fs.mkdirSync(uploadDir, { recursive: true });
    }
    cb(null, uploadDir);
  },
  filename: function (req, file, cb) {
    // 生成唯一文件名
    const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9);
    cb(null, file.fieldname + '-' + uniqueSuffix + path.extname(file.originalname));
  }
});

// 创建文件上传中间件
export const upload = multer({ 
  storage: storage,
  fileFilter: (req, file, cb) => {
    // 检查文件类型
    const allowedTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/jpg'];
    if (file.fieldname === 'avatarfile') {
      // 头像上传
      if (allowedTypes.includes(file.mimetype)) {
        cb(null, true);
      } else {
        cb(new Error('只能上传JPG、PNG或GIF格式的图片'));
      }
    } else {
      // 其他文件上传（如Excel导入）
      if (file.mimetype === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' || 
          file.mimetype === 'application/vnd.ms-excel') {
        cb(null, true);
      } else {
        cb(new Error('只允许上传Excel文件'));
      }
    }
  },
  limits: {
    fileSize: 5 * 1024 * 1024 // 5MB大小限制
  }
});

class UserController {
  /**
   * 获取所有角色和岗位列表
   * @param req 请求对象
   * @param res 响应对象
   */
  async getRolesAndPosts(req: Request, res: Response) {
    try {
      // 请求日志
      consoleLogger.info("获取角色和岗位列表请求", {
        operator: req.user?.userName || 'unknown',
      });
      
      // 获取所有角色列表
      const roles = await roleService.selectRoleAll();
      // 获取所有岗位列表
      const posts = await postService.selectPostAll();
      
      // 结果日志
      logger.info("获取角色和岗位列表成功", {
        response: {
          roles,
          posts,
        },
        operator: req.user?.userName || 'unknown',
			});
      
      ApiResponse.successWithoutWrapper(res, { roles, posts }, "操作成功", 200);
    } catch (error) {
      // 详细的错误日志
      consoleLogger.error(`获取角色和岗位列表失败: ${error instanceof Error ? error.message : String(error)}`, {
        operator: req.user?.userName || 'unknown',
        stack: error instanceof Error ? error.stack : undefined
      });
      if (!res.headersSent) {
        ApiResponse.error(res, '获取角色和岗位列表失败', 500);
      }
    }
  }

  /**
   * 获取用户列表（分页、条件）
   * @param req 请求对象
   * @param res 响应对象
   * @param next 下一个中间件
   */
  async list(req: Request, res: Response ) {
    try {
      // 请求日志
      consoleLogger.info("获取用户列表请求", {
        query: req.query,
        operator: req.user?.userName || 'unknown',
      });
      
      const result = await userService.getUserList(req.query);
      
      // 结果日志
      logger.info("获取用户列表成功", {
        response: {
          result
        },
        operator: req.user?.userName || 'unknown',
      });
      
      ApiResponse.successWithTable(res, result.rows, result.total, "查询成功", result.pageNum, result.pageSize);
    } catch (error) {
      // 详细的错误日志
      consoleLogger.error(`获取用户列表失败: ${error instanceof Error ? error.message : String(error)}`, {
        requestData: {
          query: req.query,
        },
        operator: req.user?.userName || 'unknown',
        stack: error instanceof Error ? error.stack : undefined
      });
      if (!res.headersSent) {
        ApiResponse.error(res, '获取用户列表失败', 500);
      }
    }
  }
  
  /**
   * 获取用户详细信息
   * @param req 请求对象
   * @param res 响应对象
   * @param next 下一个中间件
   */
  async getInfo(req: Request, res: Response ) {
    try {
      const userIdStr = req.params.userId;
      const userId = Number(userIdStr);
      
      // 请求日志
      consoleLogger.info("获取用户详情请求", {
        params: req.params,
        operator: req.user?.userName || 'unknown',
      });
      
      // 检查userId是否为有效数字
      if (isNaN(userId) || userId <= 0) {
        consoleLogger.warn('获取用户详情参数无效', { userId: userIdStr });
        ApiResponse.error(res, '无效的用户ID', 500);
        return;
      }
      
      const user = await userService.getUserById(userId);
      
      if (!user) {
        consoleLogger.error('获取用户详情 - 用户不存在', { userId });
        ApiResponse.error(res, '用户不存在', 500);
        return
      }
      
      // 结果日志
      logger.info("获取用户详情成功", {
        response: {
          userId: user
        },
        operator: req.user?.userName || 'unknown',
      });
      
      ApiResponse.successWithoutWrapper(res, user, "操作成功", 200);
    } catch (error) {
      // 保持详细的错误日志
      consoleLogger.error(`获取用户详情失败: ${error instanceof Error ? error.message : String(error)}`, {
        requestData: {
          params: req.params,
        },
        operator: req.user?.userName || 'unknown',
        stack: error instanceof Error ? error.stack : undefined
      });
      // 避免重复发送响应
      if (!res.headersSent) {
        ApiResponse.error(res, '获取用户详情失败', 500);
      }
    }
  }
  
  /**
   * 新增用户
   * @param req 请求对象
   * @param res 响应对象
   */
  @RepeatSubmit({ expireSeconds: 5 })
  @Log({ title: '用户管理', businessType: BusinessType.INSERT })
  async add(req: AuthRequest, res: Response ) {
    try {
      // 请求日志
      consoleLogger.info("新增用户请求", {
        body: req.body,
        operator: req.user?.userName || 'unknown',
      });
      
      // 获取操作人
      const operator = req.user?.userName || 'unknown';
      
      // 创建用户
      await userService.createUser(req.body, operator);
      
      // 结果日志
      logger.info("新增用户成功", {
        response: {
          userName: req.body.userName,
        },
        operator,
      });
      
      ApiResponse.success(res, null, '新增成功');
    } catch (error) {
      // 详细的错误日志
      consoleLogger.error(`新增用户失败: ${error instanceof Error ? error.message : String(error)}`, {
        requestData: {
          body: req.body,
        },
        operator: req.user?.userName || 'unknown',
        stack: error instanceof Error ? error.stack : undefined
      });
      if (!res.headersSent) {
        ApiResponse.error(res, '新增用户失败', 500);
      }
    }
  }
  
  /**
   * 修改用户
   * @param req 请求对象
   * @param res 响应对象
   */
  @RepeatSubmit({ expireSeconds: 5 })
  @Log({ title: '用户管理', businessType: BusinessType.UPDATE })
  async update(req: AuthRequest, res: Response ) {
    try {
      // 添加调试日志
      console.log("[用户控制器] 执行update方法");
      
      // 获取操作人
      const operator = req.user?.userName || 'unknown';
      // 请求日志
      consoleLogger.info("修改用户请求", {
        body: req.body,
        operator,
      });
      
      
      
      // 修改用户
      await userService.updateUser(req.body.userId, req.body, operator);
      
      // 结果日志
      logger.info("修改用户成功", {
        response: {
          userId: req.body.userId,
        },
        operator,
      });
      
      ApiResponse.success(res, null, '修改成功');
    } catch (error) {
      // 详细的错误日志
      consoleLogger.error(`修改用户失败: ${error instanceof Error ? error.message : String(error)}`, {
        requestData: {
          body: req.body,
        },
        operator: req.user?.userName || 'unknown',
        stack: error instanceof Error ? error.stack : undefined
      });
      if (!res.headersSent) {
        ApiResponse.error(res, '修改用户失败', 500);
      }
    }
  }
  
  /**
   * 删除用户
   * @param req 请求对象
   * @param res 响应对象
   * @param next 下一个中间件
   */
  @RepeatSubmit({ expireSeconds: 5 })
  @Log({ title: '用户管理', businessType: BusinessType.DELETE })
  async remove(req: AuthRequest, res: Response) {
    try {
      const userIds = req.params.userIds.split(',').map(id => parseInt(id));
      const operator = req.user?.userName || 'admin';
      
      // 请求日志
      consoleLogger.info("删除用户请求", { 
				params: req.params,
				operator,
			});
      
      await userService.deleteUsers(userIds, operator);
      
      // 结果日志
      logger.info("删除用户成功", {
        response: {
          userIds,
        },
        operator,
			});
      
      ApiResponse.success(res, null, '删除成功');
    } catch (error) {
      // 详细的错误日志
      consoleLogger.error(`删除用户失败: ${error instanceof Error ? error.message : String(error)}`, {
        requestData: {
          params: req.params,
        },
        operator: req.user?.userName || 'unknown',
        stack: error instanceof Error ? error.stack : undefined
      });
      if (!res.headersSent) {
        ApiResponse.error(res, '删除用户失败', 500);
      }
    }
  }
  
  /**
   * 重置密码
   * @param req 请求对象
   * @param res 响应对象
   */
  @RepeatSubmit({ expireSeconds: 5 })
  async resetPwd(req: AuthRequest, res: Response) {
    try {
      // 请求日志
      consoleLogger.info("重置密码请求", {
        body: { userId: req.body.userId }, // 不记录密码
        operator: req.user?.userName || 'unknown',
      });
      
      const { userId, password } = req.body;
      
      // 重置密码
      await userService.resetPassword(userId, password, req.user?.userName || 'unknown');
      
      // 结果日志
      logger.info("重置密码成功", {
        response: {
          userId,
        },
        operator: req.user?.userName || 'unknown',
      });
      
      ApiResponse.success(res, null, '重置成功');
    } catch (error) {
      // 详细的错误日志
      consoleLogger.error(`重置密码失败: ${error instanceof Error ? error.message : String(error)}`, {
        requestData: {
          body: { userId: req.body.userId }, // 不记录密码
        },
        operator: req.user?.userName || 'unknown',
        stack: error instanceof Error ? error.stack : undefined
      });
      if (!res.headersSent) {
        ApiResponse.error(res, '重置密码失败', 500);
      }
    }
  }
  
  /**
   * 修改用户状态
   * @param req 请求对象
   * @param res 响应对象
   */
  @RepeatSubmit({ expireSeconds: 5 })
  async changeStatus(req: AuthRequest, res: Response ) {
    try {
      // 请求日志
      consoleLogger.info("修改用户状态请求", {
        body: req.body,
        operator: req.user?.userName || 'unknown',
      });
      
      const { userId, status } = req.body;
      
      // 修改状态
      await userService.changeUserStatus(userId, status, req.user?.userName || 'unknown');
      
      // 结果日志
      logger.info("修改用户状态成功", {
        response: {
          userId,
          status,
        },
        operator: req.user?.userName || 'unknown',
      });
      
      ApiResponse.success(res, null, '修改成功');
    } catch (error) {
      // 详细的错误日志
      consoleLogger.error(`修改用户状态失败: ${error instanceof Error ? error.message : String(error)}`, {
        requestData: {
          body: req.body,
        },
        operator: req.user?.userName || 'unknown',
        stack: error instanceof Error ? error.stack : undefined
      });
      if (!res.headersSent) {
        ApiResponse.error(res, '修改用户状态失败', 500);
      }
    }
  }
  
  /**
   * 获取用户个人信息
   * @param req 请求对象
   * @param res 响应对象
   * @param next 下一个中间件
   */
  async profile(req: AuthRequest, res: Response) {
    try {
      const userId = req.user?.userId;
      // 请求日志
      consoleLogger.info("获取用户个人信息请求", {
        userId,
        operator: req.user?.userName || 'unknown',
			});
      if (!userId) {
        ApiResponse.error(res, '用户未登录', 401);
        return;
      }
      
      const user = await userService.getUserById(userId);
      if (!user) {
        ApiResponse.error(res, '用户不存在', 500);
        return;
      }
      console.log("======================");
      console.log(user);
      console.log("======================");
      
      
      // 查询角色组
      const roleGroup = await userService.selectUserRoleGroup(user.data.userName);
      // 查询岗位组
      const postGroup = await userService.selectUserPostGroup(user.data.userName);

      // 结果日志
      logger.info("获取用户个人信息成功", {
        response: {
          userId,
          user,
          roleGroup,
          postGroup,
        },
        operator: req.user?.userName || 'unknown',
			});
      ApiResponse.successWithoutWrapper(res, {
        data: user.data,
        roleGroup,
        postGroup
      }, "操作成功", 200);
    } catch (error) {
			// 详细的错误日志
			consoleLogger.error(
        `获取个人信息失败: ${error instanceof Error ? error.message : String(error)}`, {
          requestData: {
            userId: req.user?.userId || '',
          },
          operator: req.user?.userName || 'unknown',
          stack: error instanceof Error ? error.stack : undefined,
				}
			);
      if (!res.headersSent) {
        ApiResponse.error(res, "获取个人信息失败", 500);
      }
		}
  }
  
  /**
   * 修改个人信息
   * @param req 请求对象
   * @param res 响应对象
   */
  @RepeatSubmit({ expireSeconds: 5 })
  async updateProfile(req: AuthRequest, res: Response ) {
    try {
      // 获取操作人
      const operator = req.user?.userName || 'unknown';
      // 请求日志
      consoleLogger.info("修改个人信息请求", {
        body: req.body,
        operator,
      });
      
      const userId = req.user?.userId;
      if (!userId) {
        ApiResponse.error(res, '用户未登录', 401);
        return;
      } 
      
      // 更新个人信息
      await userService.updateUserProfile(userId, req.body, operator);
      
      // 结果日志
      logger.info("修改个人信息成功", {
        response: {
          userId,
        },
        operator: req.user?.userName || 'unknown',
      });
      
      ApiResponse.success(res, null, '修改成功');
    } catch (error) {
      // 详细的错误日志
      consoleLogger.error(`修改个人信息失败: ${error instanceof Error ? error.message : String(error)}`, {
        requestData: {
          body: req.body,
        },
        operator: req.user?.userName || 'unknown',
        stack: error instanceof Error ? error.stack : undefined
      });
      if (!res.headersSent) {
        ApiResponse.error(res, '修改个人信息失败', 500);
      }
    }
  }
  
  /**
   * 修改个人密码
   * @param req 请求对象
   * @param res 响应对象
   */
  @RepeatSubmit({ expireSeconds: 5 })
  async updatePwd(req: AuthRequest, res: Response ) {
    try {
      // 请求日志
      consoleLogger.info("修改个人密码请求", {
        body: { userId: req.user?.userId }, // 不记录密码
        operator: req.user?.userName || 'unknown',
      });
      
      const userId = req.user?.userId;
      if (!userId) {
        ApiResponse.error(res, '用户未登录', 401);
        return;
      }
      
      const { oldPassword, newPassword } = req.body;
      
      // 更新密码
      await userService.updatePassword(userId, oldPassword, newPassword, req.user?.userName || 'unknown');
      
      // 结果日志
      logger.info("修改个人密码成功", {
        response: {
          userId,
        },
        operator: req.user?.userName || 'unknown',
      });
      
      ApiResponse.success(res, null, '修改成功');
    } catch (error) {
      // 详细的错误日志
      consoleLogger.error(`修改个人密码失败: ${error instanceof Error ? error.message : String(error)}`, {
        requestData: {
          body: { userId: req.user?.userId }, // 不记录密码
        },
        operator: req.user?.userName || 'unknown',
        stack: error instanceof Error ? error.stack : undefined
      });
      if (!res.headersSent) {
        ApiResponse.error(res, '修改个人密码失败', 500);
      }
    }
  }
  
  /**
   * 导出用户数据
   * @param req 请求对象
   * @param res 响应对象
   * @param next 下一个中间件
   */
  async export(req: Request, res: Response ) {
    try {
      // 请求日志
      consoleLogger.info("导出用户数据请求", {
        query: req.query,
        operator: req.user?.userName || 'unknown',
      });
      
      // 获取查询参数
      const users = await userService.getUserList(req.query);
      
      // 定义导出字段
      const fields = [
        { header: '用户序号', key: 'userId', width: 10 },
        { header: '部门编号', key: 'deptId', width: 10 },
        { header: '登录名称', key: 'userName', width: 20 },
        { header: '用户名称', key: 'nickName', width: 20 },
        { header: '用户邮箱', key: 'email', width: 25 },
        { header: '手机号码', key: 'phonenumber', width: 15 },
        { header: '用户性别', key: 'sex', width: 10, type: 'select', options: { '0': '男', '1': '女', '2': '未知' } },
        { header: '账号状态', key: 'status', width: 10, type: 'select', options: { '0': '正常', '1': '停用' } },
        { header: '最后登录IP', key: 'loginIp', width: 15 },
        { header: '最后登录时间', key: 'loginDate', width: 20, type: 'datetime' },
        { header: '创建时间', key: 'createTime', width: 20, type: 'datetime' }
      ];
      
      // 直接导出到响应
      await ExcelUtil.exportToResponse(
        res,
        users.rows,
        fields,
        `user_${Date.now()}`,
        '用户数据'
      );
      logger.info("导出用户数据成功", {
        operator: req.user?.userName || 'unknown',
      });
      
      ApiResponse.success(res, null, '导出成功');
    } catch (error) {
      consoleLogger.error(`导出用户失败: ${error instanceof Error ? error.message : String(error)}`, {
        requestData: {
          query: req.query,
        },
        operator: req.user?.userName || 'unknown',
        stack: error instanceof Error ? error.stack : undefined
      });
      if (!res.headersSent) {
        ApiResponse.error(res, '导出用户失败', 500);
      }
    }
  }
  
  /**
   * 导入用户数据
   * @param req 请求对象
   * @param res 响应对象
   * @param next 下一个中间件
   */
  async importData(req: AuthRequest, res: Response ) {
    try {
      if (!req.file) {
        ApiResponse.error(res, '上传文件不能为空', 400);
        return;
      }
      
      // 请求日志
      consoleLogger.info("导入用户数据请求", {
        file: req.file,
        operator: req.user?.userName || 'unknown',
      });
      
      // 获取上传文件路径
      const filePath = req.file.path;
      
      // 获取是否支持更新的参数
      const updateSupport = req.body.updateSupport === 'true';
      
      // 定义导入字段映射
      const fields = [
        { header: '登录名称', key: 'userName' },
        { header: '用户名称', key: 'nickName' },
        { header: '用户密码', key: 'password' },
        { header: '部门编号', key: 'deptId' },
        { header: '用户邮箱', key: 'email' },
        { header: '手机号码', key: 'phonenumber' },
        { header: '用户性别', key: 'sex' },
        { header: '账号状态', key: 'status' }
      ];
      
      // 解析Excel文件
      const userList = await ExcelUtil.importExcel(filePath, fields);
      
      // 获取操作人
      const operator = req.user?.userName || 'admin';
      
      // 导入用户数据
      const message = await userService.importUser(userList, updateSupport, operator);
      
      // 导入完成后删除临时文件
      const unlinkAsync = promisify(fs.unlink);
      await unlinkAsync(filePath);

      // 结果日志
      logger.info("导入用户数据成功", {
        response: {
          message,
        },
        operator: req.user?.userName || 'unknown',
      });
      
      ApiResponse.success(res, null, message);
    } catch (error) {
      // 详细的错误日志
      consoleLogger.error(`导入用户失败: ${error instanceof Error ? error.message : String(error)}`, {
        requestData: {
          file: req.file,
          body: req.body,
        },
        operator: req.user?.userName || 'unknown',
        stack: error instanceof Error ? error.stack : undefined
      });
      if (!res.headersSent) {
        ApiResponse.error(res, `导入用户失败: ${error instanceof Error ? error.message : '未知错误'}`, 500);
      }
    }
  }
  
  /**
   * 下载导入模板
   * @param req 请求对象
   * @param res 响应对象
   * @param next 下一个中间件
   */
  async importTemplate(req: Request, res: Response ) {
    try {
      // 请求日志
      consoleLogger.info("下载导入模板请求", {
        operator: req.user?.userName || 'unknown',
      });

      // 模板数据
      const templateData = [
        {
          userName: 'admin',
          nickName: '管理员',
          password: '123456',
          deptId: 103,
          email: 'admin@example.com',
          phonenumber: '15888888888',
          sex: '1',
          status: '0'
        }
      ];
      
      // 定义模板字段
      const fields = [
        { header: '登录名称', key: 'userName', width: 20 },
        { header: '用户名称', key: 'nickName', width: 20 },
        { header: '用户密码', key: 'password', width: 20 },
        { header: '部门编号', key: 'deptId', width: 10 },
        { header: '用户邮箱', key: 'email', width: 25 },
        { header: '手机号码', key: 'phonenumber', width: 15 },
        { header: '用户性别(0男,1女,2未知)', key: 'sex', width: 20 },
        { header: '账号状态(0正常,1停用)', key: 'status', width: 20 }
      ];
      
      // 导出到响应
      await ExcelUtil.exportToResponse(
        res, 
        templateData, 
        fields, 
        `user_template_${Date.now()}`, 
        '用户数据模板'
      );

      // 结果日志
      logger.info("下载导入模板成功", {
        operator: req.user?.userName || 'unknown',
      });
      
      ApiResponse.success(res, null, '下载成功');
    } catch (error) {
      // 详细的错误日志
      consoleLogger.error(`下载导入模板失败: ${error instanceof Error ? error.message : String(error)}`, {
        operator: req.user?.userName || 'unknown',
        stack: error instanceof Error ? error.stack : undefined
      });
      if (!res.headersSent) {
        ApiResponse.error(res, '下载导入模板失败', 500);
      }
    }
  }
  
  /**
   * 根据用户编号获取授权角色
   * @param req 请求对象
   * @param res 响应对象
   * @param next 下一个中间件
   */
  async authRole(req: Request, res: Response ) {
    try {
      const userIdStr = req.params.userId;
      const userId = Number(userIdStr);

      // 请求日志
      consoleLogger.info("根据用户编号获取授权角色请求", {
        params: req.params,
        operator: req.user?.userName || 'unknown',
      });
      
      // 检查userId是否为有效数字
      if (isNaN(userId) || userId <= 0) {
        ApiResponse.error(res, '无效的用户ID', 500);
        return;
      }
      
      // 获取用户信息
      const userData = await userService.getUserById(userId);
      if (!userData) {
        ApiResponse.error(res, '用户不存在', 500);
        return;
      }
      
      // 结构完全符合预期的响应数据
      const responseData = {
        msg: "操作成功",
        code: 200,
        user: userData.data,
        roles: userData.roles
      };
      
      // 结果日志
      logger.info("根据用户编号获取授权角色成功", {
        response: {
          userId,
          rolesCount: responseData.roles?.length || 0,
        },
        operator: req.user?.userName || 'unknown',
      });
      
      // 使用API响应工具类的包装
      ApiResponse.successWithoutWrapper(res, {
        user: userData.data,
        roles: userData.roles
      }, "操作成功", 200);
    } catch (error) {
      // 详细的错误日志
      consoleLogger.error(`获取授权角色失败: ${error instanceof Error ? error.message : String(error)}`, {
        requestData: {
          params: req.params,
        },
        operator: req.user?.userName || 'unknown',
        stack: error instanceof Error ? error.stack : undefined
      });
      if (!res.headersSent) {
        ApiResponse.error(res, '获取授权角色失败', 500);
      }
    }
  }
  
  /**
   * 用户授权角色
   * @param req 请求对象
   * @param res 响应对象
   * @param next 下一个中间件
   */
  async insertAuthRole(req: AuthRequest, res: Response ) {
    try {
      const { userId, roleIds } = req.body;
      const operator = req.user?.userName || 'admin';

      // 请求日志
      consoleLogger.info("用户授权角色请求", {
        body: req.body,
        operator: req.user?.userName || 'unknown',
      });
      
      // 查询用户是否存在
      const user = await userService.getUserById(userId);
      if (!user) {
        ApiResponse.error(res, '用户不存在', 500);
        return;
      }
      
      // 更新用户角色
      await userService.updateUser(userId, { roleIds }, operator);

      // 结果日志
      logger.info("用户授权角色成功", {
        response: {
          userId,
          roleIds,
        },
        operator: req.user?.userName || 'unknown',
      });

      ApiResponse.success(res, null, '授权成功');
    } catch (error) {
      // 详细的错误日志
      consoleLogger.error(`用户授权角色失败: ${error instanceof Error ? error.message : String(error)}`, {
        requestData: {
          body: req.body,
        },
        operator: req.user?.userName || 'unknown',
        stack: error instanceof Error ? error.stack : undefined
      });
      if (!res.headersSent) {
        ApiResponse.error(res, '用户授权角色失败', 500);
      }
    }
  }

  /**
   * 获取部门树
   * @param req 请求对象
   * @param res 响应对象
   */
  async deptTree(req: Request, res: Response ) {
    try {
      // 请求日志
      consoleLogger.info("获取部门树请求", {
        operator: req.user?.userName || 'unknown',
      });

      // 获取部门树 - 不带任何查询条件获取所有部门
      const deptTree = await deptService.selectDeptTreeList({});
      
      // 确保返回一个数组，即使是空的
      const result = Array.isArray(deptTree) ? deptTree : [];

      // 结果日志
      logger.info("获取部门树成功", {
        response: {
          result,
        },
        operator: req.user?.userName || 'unknown',
      });

      ApiResponse.success(res, result);
    } catch (error) {
      // 详细的错误日志
      consoleLogger.error(`获取部门树失败: ${error instanceof Error ? error.message : String(error)}`, {
        operator: req.user?.userName || 'unknown',
        stack: error instanceof Error ? error.stack : undefined
      });
      if (!res.headersSent) {
        ApiResponse.error(res, '获取部门树失败', 500);
      }
    }
  }

  /**
   * 用户注册（无需登录）
   * @param req 请求对象
   * @param res 响应对象
   */
  @RepeatSubmit({ expireSeconds: 5 })
  @RateLimit({ limit: 3, windowSeconds: 60 })
  async register(req: Request, res: Response ) {
    try {
      // 请求日志
      consoleLogger.info("用户注册请求", {
        body: { username: req.body.username }, // 不记录密码
        operator: 'anonymous',
      });
      
      const { username, password } = req.body;
      
      // 创建用户
      const userData = {
        userName: username,
        nickName: username,
        password,
        status: '0',
        delFlag: '0',
      };
      await userService.createUser(userData, 'register');
      
      // 结果日志
      logger.info("用户注册成功", {
        response: {
          username,
        },
        operator: 'anonymous',
      });
      
      ApiResponse.success(res, null, '注册成功');
    } catch (error) {
      // 详细的错误日志
      consoleLogger.error(`注册失败: ${error instanceof Error ? error.message : String(error)}`, {
        requestData: {
          body: { username: req.body.username }, // 不记录密码
        },
        operator: 'anonymous',
        stack: error instanceof Error ? error.stack : undefined
      });
      if (!res.headersSent) {
        ApiResponse.error(res, '注册失败', 500);
      }
    }
  }

  /**
   * 获取注册开关参数（无需登录）
   * @param req 请求对象
   * @param res 响应对象
   * @param next 下一个中间件
   */
  async getRegisterConfig(req: Request, res: Response ) {
    try {
      // 请求日志
      consoleLogger.info("获取注册开关参数请求", {
        operator: req.user?.userName || 'unknown',
      });

      const registerUser = await sysConfigService.getConfigValueByKey('sys.account.registerUser');

      // 结果日志
      logger.info("获取注册开关参数成功", {
        response: {
          registerUser,
        },
        operator: req.user?.userName || 'unknown',
      });

      ApiResponse.success(res, registerUser, '查询成功');
    } catch (error) {
      // 详细的错误日志
      consoleLogger.error(`获取注册开关失败: ${error instanceof Error ? error.message : String(error)}`, {
        operator: req.user?.userName || 'unknown',
        stack: error instanceof Error ? error.stack : undefined
      });
      if (!res.headersSent) {
        ApiResponse.error(res, '获取注册开关失败', 500);
      }
    }
  }

  /**
   * 上传头像
   * @param req 请求对象
   * @param res 响应对象
   */
  async uploadAvatar(req: AuthRequest, res: Response) {
    try {
      // 请求日志
      consoleLogger.info("上传用户头像请求", {
        file: req.file,
        operator: req.user?.userName || 'unknown',
      });
      
      const userId = req.user?.userId;
      
      // 获取文件路径
      const filePath = req.file!.path.replace(/\\/g, '/');
      const fileName = req.file!.filename;
      const urlPrefix = process.env.BASE_URL || '';
      const avatarUrl = `${urlPrefix}/uploads/${filePath.split('uploads/')[1]}`;
      
      // 更新用户头像
      await userService.updateUserAvatar(userId!, avatarUrl, req.user?.userName || 'unknown');
      
      // 结果日志
      logger.info("上传用户头像成功", {
        response: {
          userId,
          avatarUrl
        },
        operator: req.user?.userName || 'unknown',
      });
      
      // 返回结果
      ApiResponse.success(res, { imgUrl: avatarUrl }, '上传成功');
    } catch (error) {
      // 详细的错误日志
      consoleLogger.error(`上传用户头像失败: ${error instanceof Error ? error.message : String(error)}`, {
        requestData: {
          file: req.file,
        },
        operator: req.user?.userName || 'unknown',
        stack: error instanceof Error ? error.stack : undefined
      });
      if (!res.headersSent) {
        ApiResponse.error(res, '上传用户头像失败', 500);
      }
    }
  }
}
export default new UserController()